<template>
    <div class="main-container">
        <!-- 警告提示 -->
        <div v-if="warningMessage" class="warning-message">
            {{ warningMessage }}
        </div>

        <div class="form-item">
            <label>患者姓名</label>
            <input v-model="form.name" type="text" placeholder="请输入患者姓名" />
        </div>

        <div class="form-item">
            <label>性别</label>
            <div class="radio-group">
                <button :class="{ active: form.gender === 0 }" @click="setGender(0)">
                    男
                </button>
                <button :class="{ active: form.gender === 1 }" @click="setGender(1)">
                    女
                </button>
            </div>
        </div>

        <!-- 出生日期 -->
        <div class="form-item">
            <label>出生年月</label>
            <div class="date-picker-container">
                <input readonly type="text" :value="formattedBirth" @click="showDatePicker = true"
                    placeholder="请输入出生日期" />
                <div v-if="showDatePicker" class="date-picker-modal">
                    <div class="date-picker-header">
                        <button @click="hideDatePicker">取消</button>
                        <button @click="confirmDatePicker">确认</button>
                    </div>
                    <div class="date-picker-body">
                        <select v-model="selectedYear">
                            <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
                        </select>
                        <select v-model="selectedMonth">
                            <option v-for="month in months" :key="month" :value="month">{{ month }}</option>
                        </select>
                        <select v-model="selectedDay">
                            <option v-for="day in days" :key="day" :value="day">{{ day }}</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-item">
            <label>体重(kg)</label>
            <input v-model.number="form.weight" type="number" min="0" placeholder="请输入体重" />
        </div>

        <div class="form-item">
            <label>过敏史</label>
            <div class="radio-group">
                <button :class="{ active: form.is_allergy === false }" @click="setAllergy(false)">
                    无
                </button>
                <button :class="{ active: form.is_allergy === true }" @click="setAllergy(true)">
                    有
                </button>
            </div>
            <div v-if="form.is_allergy === true" class="textarea-container">
                <textarea v-model="form.allergy" maxlength="50" placeholder="请填写过敏内容（最多50字）"></textarea>
            </div>
        </div>

        <div class="form-item">
            <label>过往病史</label>
            <div class="radio-group">
                <button :class="{ active: form.is_history === false }" @click="setHistory(false)">
                    无
                </button>
                <button :class="{ active: form.is_history === true }" @click="setHistory(true)">
                    有
                </button>
            </div>
            <div v-if="form.is_history === true" class="textarea-container">
                <textarea v-model="form.history" maxlength="50" placeholder="请填写病史内容（最多50字）"></textarea>
            </div>
        </div>

        <div class="form-item">
            <label>肝功能</label>
            <div class="radio-group">
                <button :class="{ active: form.is_liver === true }" @click="form.is_liver = true">
                    正常
                </button>
                <button :class="{ active: form.is_liver === false }" @click="form.is_liver = false">
                    异常
                </button>
            </div>
        </div>

        <div class="form-item">
            <label>肾功能</label>
            <div class="radio-group">
                <button :class="{ active: form.is_kidney === true }" @click="form.is_kidney = true">
                    正常
                </button>
                <button :class="{ active: form.is_kidney === false }" @click="form.is_kidney = false">
                    异常
                </button>
            </div>
        </div>

        <div class="form-item" v-if="form.gender == 1">
            <label>孕育情况</label>
            <div class="radio-group">
                <button :class="{ active: form.pregnant === 0 }" @click="setPregnant(0)">
                    无
                </button>
                <button :class="{ active: form.pregnant === 1 }" @click="setPregnant(1)">
                    怀孕中
                </button>
                <button :class="{ active: form.pregnant === 2 }" @click="setPregnant(2)">
                    哺乳中
                </button>
            </div>
        </div>

        <div class="submit-container">
            <button @click="submitForm">添加并保存</button>
        </div>
    </div>
</template>


<script setup>
import axios from "axios";
import { ElMessage } from "element-plus";
import { ref, computed } from "vue";
import { jwtDecode } from "jwt-decode";

const token = localStorage.getItem("token");
const payload = jwtDecode(token);
// console.log(payload);

const form = ref({
    name: "",
    gender: null,
    birth: "",
    weight: null,
    is_allergy: null,
    allergy: "",
    is_history: null,
    history: "",
    is_liver: null,
    is_kidney: null,
    pregnant: null,
    user: payload.user_id,
});
    

console.log(form.value);

// 出生日期
const showDatePicker = ref(false);
const warningMessage = ref(""); // 用于显示顶部警告信息
const years = Array.from({ length: 100 }, (_, i) => new Date().getFullYear() - i);
const months = Array.from({ length: 12 }, (_, i) => (i + 1).toString().padStart(2, "0"));
const selectedYear = ref(new Date().getFullYear());
const selectedMonth = ref("01");
const selectedDay = ref("01");

const formattedBirth = computed(() => {
    return form.value.birth || "请输入出生日期";
});

const days = computed(() => {
    const daysInMonth = new Date(selectedYear.value, selectedMonth.value, 0).getDate();
    return Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString().padStart(2, "0"));
});

const hideDatePicker = () => {
    showDatePicker.value = false;
};

const confirmDatePicker = () => {
    form.value.birth = `${selectedYear.value}-${selectedMonth.value}-${selectedDay.value}`;
    hideDatePicker();

    // 设置警告信息
    const birthYear = new Date(form.value.birth).getFullYear();
    const currentYear = new Date().getFullYear();
    if (currentYear - birthYear < 7) {
        warningMessage.value = "根据国家规定，患者年龄小于7岁无法开具线上处方";
    } else {
        warningMessage.value = "";
    }
};




const setGender = (value) => {
    form.value.gender = value;
    console.log(form.value);
};

const setAllergy = (value) => {
    form.value.is_allergy = value;
    if (value === true) form.value.allergy = "";
};

const setHistory = (value) => {
    form.value.is_history = value;
    if (value === true) form.value.history = "";
};

const setPregnant = (value) => {
    form.value.pregnant = value;
};

const validateForm = () => {
    const errors = [];
    if (!form.value.name) errors.push("患者姓名不能为空");
    if (form.value.gender==null) errors.push("请选择性别");
    if (!form.value.birth) errors.push("请选择出生年月");
    if (!form.value.weight) errors.push("请输入体重");
    if (form.value.is_allergy==null) errors.push("请选择过敏史");
    if (form.value.is_allergy == true && !form.value.allergy)
        errors.push("请填写过敏内容");
    if (form.value.is_history==null) errors.push("请选择过往病史");
    if (form.value.is_history == true && !form.value.history)
        errors.push("请填写过往病史内容");
    if (form.value.is_liver==null) errors.push("请选择肝功能状态");
    if (form.value.is_kidney==null) errors.push("请选择肾功能状态");

    // if (form.value.pregnant == null) errors.push("请选择孕育情况");
    

    return errors;
};

const submitForm = () => {
    const errors = validateForm();
    if (errors.length > 0) {
        // alert(errors.join("\n"));
        ElMessage.error(errors[0]);
        return;
    }
    axios.post("http://127.0.0.1:8000/patient/patient/", form.value, {
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,  
        },
    }).then((res) => {
        ElMessage.success("添加成功！");
        window.location = "/patient";
    })
    
};
</script>

<style scoped>
.main-container {
    max-width: 500px;
    margin: 0 auto;
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-item {
    margin-bottom: 20px;
}

label {
    display: block;
    font-size: 14px;
    margin-bottom: 5px;
}

.date-picker-container {
    position: relative;
}

input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
}

.date-picker-modal {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 10px;
}

.date-picker-header {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #ccc;
}

.date-picker-header button {
    background: none;
    border: none;
    font-size: 14px;
    color: #42b983;
    cursor: pointer;
}

.date-picker-body {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
}

select {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
}

.radio-group {
    display: flex;
    gap: 10px;
}

.radio-group button {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #f7f7f7;
    cursor: pointer;
    color: #000;
}

.radio-group button.active {
    background: #42b983;
    color: #fff;
    border-color: #42b983;
}

.textarea-container {
    margin-top: 10px;
    position: relative;
}

.submit-container {
    text-align: center;
    
}

textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    height: 100px;
    resize: none;
}

button {
    padding: 10px 20px;
    background: #42b983;
    color: #fff;
    border: none;
    border-radius: 20px;
    cursor: pointer;
    width: 100%;
}

.warning-message {
    background-color: #fadb96;
    color: #353534;
    padding: 10px;
    margin-bottom: 20px;
    border-radius: 5px;
    text-align: center;
    font-size: 14px;
}
</style>
